package com.cn.xiaonuo.slbfinances.slbagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.AgentConstant;
import com.cn.xiaonuo.common.constant.SystemConstant;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.AgentUtils;
import com.cn.xiaonuo.common.utils.StringUtils;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.members.entity.SlUser;
import com.cn.xiaonuo.slbfinances.members.mapper.SlUserMapper;
import com.cn.xiaonuo.slbfinances.slbagents.entity.SlXsHpcBuy;
import com.cn.xiaonuo.slbfinances.slbagents.entity.SlXsProxyData;
import com.cn.xiaonuo.slbfinances.slbagents.mapper.SalesOperationsMapper;
import com.cn.xiaonuo.slbfinances.slbagents.mapper.SlXsHpcBuyMapper;
import com.cn.xiaonuo.slbfinances.slbagents.mapper.SlXsProxyDataMapper;
import com.cn.xiaonuo.slbfinances.slbagents.service.ISalesOperationsService;
import com.cn.xiaonuo.slbfinances.slbagents.service.SlbOperationsService;
import com.cn.xiaonuo.slbfinances.slbagents.service.XsProxyDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SalesOperationsServiceImpl extends ServiceImpl<SalesOperationsMapper, String> implements ISalesOperationsService {

    @Resource
    private SalesOperationsMapper salesOperationsMapper;
    @Resource
    private XsProxyDataService xsProxyDataService;
    @Resource
    private SlUserMapper slUserMapper;
    @Resource
    private SlXsHpcBuyMapper slXsHpcBuyMapper;
    @Autowired
    private SlbOperationsService slbOperationsService;

    //查看代理条件进度
    @Override
    @DataSource(name = "hpc_agent_db")
    public BusinessMessage queryAgentCondition(String userId) {
        BusinessMessage message = new BusinessMessage();
        try {
            //0.获得当前周期的开始结束时间
            Map<String, Object> mapPayment = AgentUtils.queryCycleTime();
            String startTime = mapPayment.get("startTime").toString();
            String endTime = mapPayment.get("endTime").toString();

            //1.判断必填参数不能为空。
            if (StringUtils.isBlank(userId)) {
                message.setSuccess(false);
                message.setMessage("必填参数userId不能为空");
                return message;
            }

            //2.查询直接下级本周有10瓶酒以上消费的人数【陈】
            List<Map<String, Object>> map = salesOperationsMapper.queryDownUserBuy(userId, "week", startTime, endTime);
            int consumeNum = 0;//本周10瓶消费以上的人数默认值0
            if (map != null && map.size() > 0) {
                consumeNum = map.size();
            }

            //3.查询他自己是否本周消费10瓶酒【陈】
            List<Map<String, Object>> map2 = salesOperationsMapper.queryOwnBuy(userId, "week", startTime, endTime);
            int ownConsume = 0;//默认自己本周未消费
            if (map2 != null && map2.size() > 0) {
                ownConsume = 1;
            }

            //4.查看累计兑酒数
            proxyData(userId);//更新兑酒数
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.setEntity(new SlXsProxyData() {{
                setUserId(Integer.valueOf(userId));
            }});
            SlXsProxyData slXsProxyData = xsProxyDataService.queryOne(userId);
            Integer wineNum = 0;//累计兑酒数默认值
            if (slXsProxyData != null) {
                wineNum = slXsProxyData.getCumulativeNumber();
            }

            //5.查询下级中区代人数
            int quNum = 0;//区代默认值
            List<Map<String, Object>> quMaps = salesOperationsMapper.queryZjSalesOperations(userId, "1");
            if (quMaps != null && quMaps.size() > 0) {
                quNum = quMaps.size();//区代人数
            }

            //6.查询下级中市代人数
            int shiNum = 0;//市代默认值
            List<Map<String, Object>> shiMaps = salesOperationsMapper.queryZjSalesOperations(userId, "2");
            if (shiMaps != null && shiMaps.size() > 0) {
                shiNum = shiMaps.size();//区代人数
            }

            //7.查询下级中省代人数
            int shengNum = 0;//市代默认值
            List<Map<String, Object>> shengMaps = salesOperationsMapper.queryZjSalesOperations(userId, "3");
            if (shengMaps != null && shengMaps.size() > 0) {
                shengNum = shengMaps.size();//省代人数
            }

            //8.当前代理级别
            SlUser slUser = slUserMapper.selectById(userId);
            int agentType = -1;
            if (slUser != null) {
                agentType = slUser.getAgent();
            }

            //9.查询下级中省市区达成条件的人
            List<Map<String, Object>> conditionLowerList = salesOperationsMapper.queryConditionLower(userId);
            Integer conditionLowerNum = 0;
            if (conditionLowerList != null && conditionLowerList.size() > 0) {
                conditionLowerNum = conditionLowerList.size();
            }

            //10.查询自己是否能获得提成
            List<Map<String, Object>> queryConditionOwnList = salesOperationsMapper.queryConditionOwn(userId);
            Integer conditionOwn = 0;
            if (queryConditionOwnList != null && queryConditionOwnList.size() > 0) {
                conditionOwn = 1;//符合提成
            }

            //11.查询本周期所有无穷下级+本人在和平村购买量
            updateHpcBuyAmount(userId, startTime, endTime);
            queryWrapper.setEntity(new SlXsHpcBuy() {{
                setUserId(Integer.parseInt(userId));
            }});
            SlXsHpcBuy slXsHpcBuy = slXsHpcBuyMapper.selectOne(queryWrapper);
            Integer buyAmount = 0;
            if (slXsHpcBuy != null) {
                buyAmount = slXsHpcBuy.getBuyAmount();
            }

            //12.封装数据 账号异常已被锁定
            Map<String, Object> data = new HashMap<>();
            data.put("phone", slUser.getPhone());
            data.put("buyAmount", buyAmount);
            data.put("consumeNum", consumeNum);
            data.put("consumeDetail", map);
            data.put("ownConsume", ownConsume);
            data.put("wineNum", wineNum);
            data.put("quNum", quNum);
            data.put("quUserList", quMaps);
            data.put("shiNum", shiNum);
            data.put("shiUserList", shiMaps);
            data.put("shengNum", shengNum);
            data.put("shengUserList", shengMaps);
            data.put("agentType", agentType);
            data.put("conditionLowerNum", conditionLowerNum);//符合提成条件的下级数量
            data.put("conditionLowerList", conditionLowerList);//符合提成条件的下级明细
            data.put("conditionOwn", conditionOwn);//自己是否符合提成条件，0不符合，1符合
            data.put("startTime", startTime);//本周期开始时间
            data.put("endTime", endTime);//本周期结束时间
            message.setMessage("操作成功");
            message.setSuccess(true);
            message.setData(data);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }

    //连接搜了宝数据库，更新hpc_buy_amount的数据
    @DataSource(name = "hpc_agent_db")
    public void updateHpcBuyAmount(String userId, String beginTime, String endTime) {
        try {
            //获取数据
            List<Map<String,String>> buyList=slbOperationsService.getSlbProxyBuyAmount(userId,beginTime,endTime);
            for(Map<String,String> buyMap:buyList) {
                String buyAmount = buyMap.get("buyAmount");
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.setEntity(new SlXsHpcBuy() {{
                    setUserId(Integer.parseInt(userId));
                }});
                //往sl_xs_hpc_buy中加数据
                SlXsHpcBuy slXsHpcBuy = slXsHpcBuyMapper.selectOne(queryWrapper);
                if (slXsHpcBuy == null) {
                    //给用户添加下级购买数
                    slXsHpcBuy = new SlXsHpcBuy();
                    slXsHpcBuy.setUserId(Integer.parseInt(userId));
                    slXsHpcBuy.setBuyAmount(Double.valueOf(buyAmount).intValue());
                    slXsHpcBuyMapper.insert(slXsHpcBuy);
                } else {
                    slXsHpcBuy.setBuyAmount(Double.valueOf(buyAmount).intValue());
                    slXsHpcBuyMapper.updateById(slXsHpcBuy);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //连接8.0数据库，更新sl_xs_proxy_data的数据
    @DataSource(name = "hpc_agent_db")
    public void proxyData(String userId) {
        try {
            //获取数据
            String user_id = "";
            String area_generation = "";
            String generation = "";
            String provincial_generation = "";
            String cumulative_number = "";
            String Against_number = "";
            Map<String,String> slbAgentMap=slbOperationsService.getSlbProxyData(userId);
            if(slbAgentMap!=null){
               // user_id = slbAgentMap.get("user_id");
                area_generation = slbAgentMap.get("area_generation");
                generation = slbAgentMap.get("generation");
                provincial_generation = slbAgentMap.get("provincial_generation");
                cumulative_number = slbAgentMap.get("cumulative_number");
                Against_number = slbAgentMap.get("Against_number");
            }
            //往sl_xs_proxy_data中加数据
            SlXsProxyData slXsProxyData = xsProxyDataService.queryOne(userId);
            if (slXsProxyData == null) {
                slXsProxyData = new SlXsProxyData();
                slXsProxyData.setUserId(Integer.valueOf(userId));
                slXsProxyData.setAreaGeneration(Integer.valueOf(area_generation));
                slXsProxyData.setGeneration(Integer.valueOf(generation));
                slXsProxyData.setProvincialGeneration(Integer.valueOf(provincial_generation));
                slXsProxyData.setCumulativeNumber(Integer.valueOf(cumulative_number));
                slXsProxyData.setAgainstNumber(Integer.valueOf(Against_number));
                slXsProxyData.setCumulativeRegister(0);
                slXsProxyData.setRegisterToday(0);
                xsProxyDataService.add(slXsProxyData);
            } else {
                slXsProxyData.setUserId(Integer.valueOf(userId));
                slXsProxyData.setAreaGeneration(Integer.valueOf(area_generation));
                slXsProxyData.setGeneration(Integer.valueOf(generation));
                slXsProxyData.setProvincialGeneration(Integer.valueOf(provincial_generation));
                slXsProxyData.setCumulativeNumber(Integer.valueOf(cumulative_number));
                slXsProxyData.setAgainstNumber(Integer.valueOf(Against_number));
                xsProxyDataService.edit(slXsProxyData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    //提成用户列表
    @DataSource(name = "hpc_agent_db")
    public BusinessMessage agentUserList(String paymentUserId, String realName,
                                         String startTime, String endTime,
                                         Integer pageNum, Integer pageSize) {
        BusinessMessage message = new BusinessMessage();
        try {
            //0.时间转换
            if (StringUtils.isNotBlank(startTime)) {
                startTime = SystemConstant.SDF.format(new Date(new Long(startTime)));
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTime = SystemConstant.SDF.format(new Date(new Long(endTime)));
            }
            //设置默认时间
            if (StringUtils.isBlank(startTime)) {
                startTime = "1900-01-01 00:00:00";
            }
            if (StringUtils.isBlank(endTime)) {
                endTime = "2900-01-01 00:00:00";
            }

            //1.设置默认分页参数
            if (null == pageNum || pageNum <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }

            //2.执行查询
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> royaltyList = salesOperationsMapper.agentUserList(
                    paymentUserId, realName, startTime, endTime
            );
            PageInfo<Map<String, Object>> data = new PageInfo<>(royaltyList);

            //3.返回数据
            message.setData(data);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }

    @Override
    //结款用户订单明细
    @DataSource(name = "hpc_agent_db")
    public BusinessMessage paymentOrderList(String paymentUserId, String startTime, String endTime, Integer pageNum, Integer pageSize, String buyerName, String productName) {
        BusinessMessage message = new BusinessMessage();
        try {
            //0.时间转换
            if (StringUtils.isNotBlank(startTime)) {
                startTime = SystemConstant.SDF.format(new Date(new Long(startTime)));
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTime = SystemConstant.SDF.format(new Date(new Long(endTime)));
            }
            //设置默认时间
            if (StringUtils.isBlank(startTime)) {
                startTime = "1900-01-01 00:00:00";
            }
            if (StringUtils.isBlank(endTime)) {
                endTime = "2900-01-01 00:00:00";
            }
            //设置结款状态
            String paymentState = "0";

            //1.设置默认分页参数
            if (null == pageNum || pageNum <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }

            //2.执行查询
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> royaltyList = salesOperationsMapper.paymentOrderList(
                    paymentUserId, paymentState, startTime, endTime, buyerName, productName
            );
            PageInfo<Map<String, Object>> data = new PageInfo<>(royaltyList);

            //3.返回数据
            message.setData(data);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }
    @Override
    //提成用户订单明细
    @DataSource(name = "hpc_agent_db")
    public BusinessMessage agentOrderList(String paymentUserId, String startTime, String endTime,
                                          Integer pageNum, Integer pageSize, String buyerName,
                                          String productName, String paymentStartTime,
                                          String paymentEndTime, String paymentState) {
        BusinessMessage message = new BusinessMessage();
        try {
            //0.时间转换
            if (StringUtils.isNotBlank(startTime)) {
                startTime = SystemConstant.SDF.format(new Date(new Long(startTime)));
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTime = SystemConstant.SDF.format(new Date(new Long(endTime)));
            }
            if (StringUtils.isNotBlank(paymentStartTime)) {
                paymentStartTime = SystemConstant.SDF.format(new Date(new Long(paymentStartTime)));
            }
            if (StringUtils.isNotBlank(paymentEndTime)) {
                paymentEndTime = SystemConstant.SDF.format(new Date(new Long(paymentEndTime)));
            }
            //设置默认时间
            if (StringUtils.isBlank(startTime)) {
                startTime = "1900-01-01 00:00:00";
            }
            if (StringUtils.isBlank(endTime)) {
                endTime = "2200-01-01 00:00:00";
            }

            //1.设置默认分页参数
            if (null == pageNum || pageNum <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }

            //2.执行查询
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> royaltyList = salesOperationsMapper.agentOrderList(
                    paymentUserId, paymentState, startTime, endTime, buyerName, productName, paymentStartTime, paymentEndTime
            );
            PageInfo<Map<String, Object>> data = new PageInfo<>(royaltyList);

            //3.返回数据
            message.setData(data);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }
    @Override
    //提成用户订单明细
    @DataSource(name = "hpc_agent_db")
    //结款用户列表
    public BusinessMessage paymentUserList(String paymentUserId,String realName,String startTime,String endTime,Integer pageNum, Integer pageSize){
        BusinessMessage message = new BusinessMessage();
        try {
            //0.时间转换
            if (StringUtils.isNotBlank(startTime)) {
                startTime = SystemConstant.SDF.format(new Date(new Long(startTime)));
            }
            if (StringUtils.isNotBlank(endTime)) {
                endTime = SystemConstant.SDF.format(new Date(new Long(endTime)));
            }
            //设置默认时间
            if(StringUtils.isBlank(startTime)){
                startTime = "1900-01-01 00:00:00";
            }
            if(StringUtils.isBlank(endTime)){
                endTime = "2200-01-01 00:00:00";
            }

            //1.设置默认分页参数
            if (null == pageNum || pageNum <= 1) {
                pageNum = 1;
            }
            if (null == pageSize || pageSize <= 1) {
                pageSize = 10;
            }
            //2.执行查询
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> royaltyList = salesOperationsMapper.paymentUserList(
                    paymentUserId, realName, startTime, endTime
            );
            PageInfo<Map<String, Object>> data = new PageInfo<>(royaltyList);
            //3.返回数据
            message.setData(data);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            message.setSuccess(false);
            message.setMessage("操作失败");
            return message;
        }
    }








}
